<template>
  <div class="m-3">
    <Card>
      <div class="text-xl pb-2">产品分组展示管理</div>
      <Tabs v-model:activeKey="activeKey" type="editable-card" :hide-add="groupList.length >= 15" @edit="handTabsEdit">
        <TabPane v-for="item in groupList" :key="item.id" :tab="item.name" :closable="!item.groupType">
          <div class="p-4 bg-[#F7F8FA]" style="margin-top: -16px">
            <Card title="分组信息">
              <template #extra>
                <Button type="primary" ghost size="small" @click="handGroupEdit(item)">
                  <EditOutlined key="edit" />
                  修改
                </Button>
              </template>
              <Form
                :model="item"
                :label-col="{ style: { width: '150px' } }"
                :wrapper-col="{ style: { width: 'calc(100% - 150px)' } }"
              >
                <FormItem label="分组名称">
                  {{ item.name }}
                </FormItem>
                <FormItem label="产品展示样式：">
                  {{ item.styleType === ProductDisplay.GRID ? '宫格列表' : '横向列表' }}
                  <img v-if="item.styleType === ProductDisplay.GRID" src="@/assets/images/grid.png" class="mt-2" />
                  <img v-else src="@/assets/images/row.png" class="mt-2" />
                </FormItem>
              </Form>
            </Card>

            <Card v-if="!item.groupType" title="分组产品管理" style="margin-top: 12px" :bodyStyle="{padding: 0}">
              <template #extra>
                <Button type="primary" ghost size="small" @click="handProductAdd(item)">
                  <PlusOutlined key="add" />
                  添加产品
                </Button>
              </template>

              <ProductList :groupId="item.id" :activeKey="activeKey" :refreshTable="refreshTable" />
            </Card>
          </div>
        </TabPane>
      </Tabs>
    </Card>

    <div class="my-3 bg-white p-3 text-right">
      <Space>
        <Button @click="lastStep">上一步</Button>
        <Button type="primary" @click="goBackList">完成配置</Button>
      </Space>
    </div>

    <EditPlateGroup @register="registerEditPlateGroup" @refresh="getTemplateGroupList" />

    <SelectProduct @register="registerSelectProduct" @ok="handSelectProductOk" />
  </div>
</template>

<script lang="ts" setup>
  import { Card, Button, Form, FormItem, Space, Tabs, TabPane, Modal } from 'ant-design-vue';
  import { ref, unref, watch } from 'vue';
  import { useModal } from '@/components/Modal';
  import { TemplateGroupItem } from '@/api/hby/resourceLeague/type';
  import {
    getMerchantTemplateGroupConfig,
    removeMerchantTemplateGroup,
    merchantTemplateGroupAddProduct
  } from '@/api/hby/resourceLeague/index';
  import { useRouter } from 'vue-router';
  import { EditOutlined, PlusOutlined } from '@ant-design/icons-vue';
  import { useMessage } from '@/hooks/web/useMessage';
  import EditPlateGroup from '../components/editPlateGroup.vue'
  import { ProductDisplay } from '@/enums/resourceLeague';

  import ProductList from './product.vue'
  import SelectProduct from '../components/selectProduct.vue';
  import { router } from '@/router';


  const emit = defineEmits(['lastStep']);

  const { currentRoute } = useRouter();

  const groupList = ref<TemplateGroupItem[]>([]);
  const activeKey = ref<number>();
  function getTemplateGroupList() {
    const { id } = currentRoute.value.query;
    getMerchantTemplateGroupConfig(id).then((res) => {
      groupList.value = res;
    });
  }
  getTemplateGroupList();

  watch(
    () => groupList.value,
    (list) => {
      const findItem = list.find((v) => v.id === unref(activeKey));
      if(!findItem){
        activeKey.value = undefined;
      }
      if(!unref(activeKey) && list.length){
        activeKey.value = list[0].id;
      }
    },
    { deep: true }
  )

  // 新增 || 删除分组
  const { createMessage } = useMessage();
  
  const [registerEditPlateGroup, { openModal: openModalEditPlateGroup }] = useModal();
  function handTabsEdit(targetKey: number | MouseEvent, action: string) {
    if (action === 'remove') {
      Modal.confirm({
        title: '移除该分组',
        content: '确定要将分组移除吗？',
        cancelText: '暂不移除',
        okText: '确定移除',
        onOk: async () => {
          return new Promise<void>((resolve, reject) => {
            removeMerchantTemplateGroup(targetKey as number).then(() => {
              groupList.value = groupList.value.filter((v) => v.id !== targetKey);
              createMessage.success('删除成功');
              resolve();
            }).catch((err)=>{
              reject(err);
            })
          });
        },
      });


      
    } else {
      // 打开新增分组弹窗
      openModalEditPlateGroup(true, {
        name: "",
        styleType: ProductDisplay.GRID
      })
    }
  };
  // 编辑分组
  function handGroupEdit(item){
    openModalEditPlateGroup(true, item)
  };


  // 打开选择产品弹窗
  const refreshTable = ref(false);
  const [registerSelectProduct, { openModal: openModalSelectProduct }] = useModal();
  function handProductAdd(item) {
    refreshTable.value = false;
    openModalSelectProduct(true, item);
  }
  function handSelectProductOk(params) {
    // 添加产品
    merchantTemplateGroupAddProduct({
      groupId: params.groupId,
      productIds: params.rows.map(v=> v.id)
    }).then(()=>{
      createMessage.success('添加成功');
      refreshTable.value = true; // 刷新表格
    })
  }


  function lastStep() {
    emit('lastStep');
  }

  function goBackList() {
    router.back();
  }
</script>

<style lang="less" scoped></style>
